package com.szyjjk.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.szyjjk.util.DateUtil;
import com.szyjjk.util.FileUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletResponse;

@Controller
public class OffLineController {

	@Value("${downOffLinePath}")
	private String downOffLinePath;
	@Value("${offLine}")
	private Integer offLine;

	private static Logger logger = LoggerFactory.getLogger(OffLineController.class);

	@RequestMapping(value = "/offLine/downSql.do")
	public void down(HttpServletResponse response) {
		if (offLine == 1) {
			response.setStatus(1001);
		}

		String sql = downOffLinePath + "szyjjk.sql";

		try {
			// 备份数据量
			File datafile = new File(sql);
			long time = DateUtil.getDateMin().getTime();
			if (datafile.exists()) {
				long lastModified = datafile.lastModified();
				// 文件创建时间小于今天最小时间 要更新sql
				if (lastModified < time) {
					datafile.delete();
					getSql(sql);
				}else {
					getSql(sql);
				}
			}else {
				getSql(sql);
			}
			// 读到流中
			InputStream inStream = new FileInputStream(sql);// 文件的存放路径
			// 设置输出的格式
			response.reset();
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition", "attachment; filename=\"" + "szyjjk.sql" + "\"");
			response.setStatus(200);
			// 循环取出流中的数据
			byte[] b = new byte[1024];
			int len;
			while ((len = inStream.read(b)) > 0)
				response.getOutputStream().write(b, 0, len);
			inStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 下载离线的 手动 已经打包好的zip
	 * 
	 * @param response
	 */
	@RequestMapping(value = "/offLine/downZip.do")
	public void downZip(HttpServletResponse response) {
		if (offLine == 1) {
			//本身是离线包的时候不能再下载
			response.setStatus(1001);
		}
		// 到之前备份最新数据库
		String fileName = "WateraModels.zip";
		String fileDownLoadPath = downOffLinePath + fileName;

		try {
			// 读到流中
			InputStream inStream = new FileInputStream(fileDownLoadPath);// 文件的存放路径
			// 设置输出的格式
			response.reset();
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
			response.setStatus(200);
			// 循环取出流中的数据
			byte[] b = new byte[1024];
			int len;
			while ((len = inStream.read(b)) > 0)
				response.getOutputStream().write(b, 0, len);
			inStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void getSql(String sql) throws IOException, InterruptedException {
		// 拼接cmd命令 需配置数据库环境变量
		String cmd = "cmd /c mysqldump  -u " + "root" + " -p" + "123456" + " " + "szyjjk" + " > " + sql;
		Process exec = Runtime.getRuntime().exec(cmd);
		if (exec.waitFor() == 0) {
			logger.info("数据库备份成功,备份路径为： " + sql);
		}
//		String content = "\r\n DELETE FROM  run_file_path;\r\n" + "DELETE FROM  run_his_data;\r\n"
//				+ "DELETE FROM  run_map_pic;\r\n DELETE FROM  run_map_shp";
//		FileUtil.appendContent(sql, content);
	}
// 打包zip 代码 暂时无用
//	private void getZip(String fileName) {
//		ArrayList<File> files = getFiles(downOffLinePath);
//		Map<String, String> bases = new HashMap<>();
//		for (int i = 0; i < files.size(); i++) {
//			File s = files.get(i);
//			String value = s.getPath().substring(s.getPath().indexOf("\\") + 1); // 转为相对路径
//			String filePathName = value.substring(0, value.lastIndexOf("\\"));
//			bases.put(s.getAbsolutePath(), filePathName);
//		}
//		File zip = new File(downOffLinePath + fileName);
//		TarUtils.zipFileFolders(files, zip, bases);
//	}
//
//	public ArrayList<File> getFiles(String path) {
//		ArrayList<File> files = new ArrayList<File>();
//		File file = new File(path);
//		File[] tempList = file.listFiles();
//		for (int i = 0; i < tempList.length; i++) {
//			if (tempList[i].isFile()) {
//				files.add(tempList[i]);
//			}
//			if (tempList[i].isDirectory()) {
//				ArrayList<File> files1 = getFiles(tempList[i].getPath());
//				files.addAll(files1);
//			}
//		}
//		return files;
//	}
}
